#!/bin/sh

freshurl(){
    for i in `cat url.txt`
    do
        fname=`basename $i`
        if [ -f $fname ] && [ ! -f $fname.aria2 ];then
            sed -i "/$fname/d" url.txt
        fi
    done
    echo "begin download..."
}

joinurl(){
    if echo $2 | grep ^/ > /dev/null; then
        nxturl=`echo $1 | awk -F'/' '{print($1"/"$2"/"$3)}'`$2
        echo $nxturl
    else
	    echo `dirname $1`/$2
    fi
}


M3U8=$1
destname=`basename $2`
ddir=$2.d
mkdir $ddir
curdir=`pwd`
cd $ddir
echo $M3U8
#sleep 1
wget --no-check-certificate "$M3U8" -O index.m3u8
grep -v '^#' index.m3u8  > url.txt
nexturl=`grep '\.m3u8$' url.txt`
echo nexturi=$nexturl
if [ "$nexturl" != '' ]; then
    M3U8=$(joinurl "$M3U8" $nexturl)
    echo nexurl=$M3U8
    wget --no-check-certificate "$M3U8" -O index.m3u8
    grep -v '^#' index.m3u8  > url.txt
fi

host=`echo $M3U8 | awk -F'/' '{print($1"/"$2"/"$3)}'`
parenturl=`dirname $M3U8`

echo host=$host
echo parenturl=$parenturl

keyuri=$(grep 'EXT-X-KEY' index.m3u8 | grep -v NONE | sed 's/.*URI="//' | sed 's/"//')
echo keyuri=$keyuri
if [ "$keyuri" != '' ]; then
    echo "prepare download key"
    echo $keyuri | grep '^/' && wget --no-check-certificate $host$keyuri || wget --no-check-certificate $parenturl/$keyuri
else
    echo "nokey"
fi

prefix_ts_url_sample=$(head -1 url.txt)
if [ ${prefix_ts_url_sample:0:4} == 'http' ] || [ ${prefix_ts_url_sample:0:1} == '/' ]; then
    sed -i "/xx\.ts/d;s?^/?$parenturl/?;s?^/?$host/?" url.txt
else
    sed -i "s?^?$parenturl/?" url.txt
fi

echo "begin refreshdownload..."
while true;do
    freshurl
    aria2c -i url.txt

    if [ $? -eq 0 ];then
        break
    fi
    echo "<>><><><><><><><><download failed!!!!!!!!!!!!!!"
done

sed -i "s?http.*/??;s/?.*//" index.m3u8

ffmpeg -protocol_whitelist "file,http,crypto,tcp" -allowed_extensions ALL -i index.m3u8  -c copy $destname
if [ $? -eq 0 ];then
    cd $curdir
    mv $ddir/$destname $2
    rm -rf $ddir
else
    exit 255
fi
